/*
 * Adds a command tiny to convert a URL with TinyURL
 * Copyright (C) 2009 Igor Neri <igor@gmx.it>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301, USA.
 */

#include "include/pp_internal.h"

#include <time.h>
#include <stdlib.h>

#include <cmds.h>
#include <conversation.h>
#include <debug.h>
#include <plugin.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>

struct MemoryStruct {
  char *memory;
  size_t size;
};

static void *myrealloc(void *ptr, size_t size);
  
static void *myrealloc(void *ptr, size_t size)
{
	  /* There might be a realloc() out there that doesn't like reallocing
	   *      NULL pointers, so we take care of it here */
	  if(ptr)
		      return realloc(ptr, size);
	    else
		        return malloc(size);
}

static size_t
WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
  size_t realsize = size * nmemb;
  struct MemoryStruct *mem = (struct MemoryStruct *)data;

  mem->memory = myrealloc(mem->memory, mem->size + realsize + 1);
  if (mem->memory) {
    memcpy(&(mem->memory[mem->size]), ptr, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;
  }
  return realsize;
}

char* url2tiny(char *url)
{
  CURL *curl_handle;
  char *tiny;
  char *tempstr;
  char *tinyurl;
  struct MemoryStruct chunk;

  tinyurl = (char*) malloc (strlen(url)+35);
  strcpy(tinyurl,"http://tinyurl.com/create.php?url=");
  strcat(tinyurl,url);

  chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
  chunk.size = 0;    /* no data at this point */

  curl_global_init(CURL_GLOBAL_ALL);

  curl_handle = curl_easy_init();
  curl_easy_setopt(curl_handle, CURLOPT_URL, tinyurl);
  curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
  curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
  curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
  curl_easy_perform(curl_handle);
  curl_easy_cleanup(curl_handle);

  tempstr = strdup(strstr(chunk.memory, "[<a href=\"")+10);
  tiny=strndup(tempstr,(int) (strchr(tempstr, '"') - tempstr));

  free(chunk.memory);
  free(tinyurl);
  free(tempstr);

  curl_global_cleanup();

  return tiny;
}

static PurpleCmdId tiny_cmd_id = 0;

static PurpleCmdRet
roll(PurpleConversation *conv, const gchar *cmd, gchar **args, gchar *error,
	 void *data)
{
	PurpleCmdStatus ret;
	gchar *str = NULL, *newcmd = NULL;

	if(!args[0]) {
		str = g_strdup("");;
	} else {
		str = g_strdup(url2tiny(args[0]));
	}

	newcmd = g_strdup_printf("say %s", str);

	ret = purple_cmd_do_command(conv, newcmd, newcmd, &error);

	g_free(str);
	g_free(newcmd);

	return ret;
}

static gboolean
plugin_load(PurplePlugin *plugin)
{
	const gchar *help;

	help = _("tiny:  replace the URL passed as argument with the\n"
			 "TinyURL generated");

	tiny_cmd_id = purple_cmd_register("tiny", "wws", PURPLE_CMD_P_PLUGIN,
					PURPLE_CMD_FLAG_IM | PURPLE_CMD_FLAG_CHAT |
					PURPLE_CMD_FLAG_ALLOW_WRONG_ARGS,
					NULL, PURPLE_CMD_FUNC(roll),
					help, NULL);
	return TRUE;
}

static gboolean
plugin_unload(PurplePlugin *plugin)
{
	purple_cmd_unregister(tiny_cmd_id);
	return TRUE;
}

static PurplePluginInfo info =
{
	PURPLE_PLUGIN_MAGIC,
	PURPLE_MAJOR_VERSION,
	PURPLE_MINOR_VERSION,
	PURPLE_PLUGIN_STANDARD,	
	NULL,
	0,
	NULL,
	PURPLE_PRIORITY_DEFAULT,

	"core-tinyurl",
	NULL,
	"0.1",	
	NULL,
	NULL,
	"Igor Neri <higor@gmx.it>",	
	"http://code.google.com/p/pidgin-tinyurl/",	

	plugin_load,
	plugin_unload,
	NULL,

	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL
};

static void
init_plugin(PurplePlugin *plugin)
{
#ifdef ENABLE_NLS
	bindtextdomain(GETTEXT_PACKAGE, PP_LOCALEDIR);
	bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
#endif /* ENABLE_NLS */

	info.name = _("tiny");
	info.summary = _("Transform URL with tinyurl");
	info.description = _("Adds a command (/tiny) to transform a "
				 "url in tinyurl.");

}

PURPLE_INIT_PLUGIN(tiny, init_plugin, info)
